package com.yhb.hash.tcpdemo;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerThread extends Thread{
    @Override
    public void run() {
        try {
            //服务器ServerSocket
            ServerSocket serverSocket=new ServerSocket(9903);
            //死循环，服务器一直处于运转状态
            while (true){
                //创建一个用于接受客户端的socket
                Socket socket=serverSocket.accept();
                //使用socket和客户端进行通信
                ////////////接收消息///////////////
                //获取socket的输入流对象
                BufferedReader bufferedReader=new BufferedReader(
                        new InputStreamReader(socket.getInputStream(),"UTF-8")
                );
                //读取信息
                while(true){
                    String str=bufferedReader.readLine();
                    //如果读取到了规定结束符 则结束读取
                    if(str!=null&&!str.equals("eof")){
                        //业务逻辑处理的地方
                        System.out.println("服务器:"+str);
                    }else{
                        //终止循环读取信息
                        break;
                    }
                }

                /////////////发送信息//////////
                //获取socket的输出流对象
                BufferedWriter bufferedWriter=new BufferedWriter(
                        new OutputStreamWriter(socket.getOutputStream(),"utf-8")
                );
                //发送的消息
                String strMsg="nihao too,客户端~~~~~~~~~~";
                System.out.println("服务器："+strMsg);
                bufferedWriter.write(strMsg);
                //附加一个回车符
                bufferedWriter.newLine();
                //自定义一个通信协议：消息发送末尾 使用eof结束
                bufferedWriter.write("eof");
                bufferedWriter.write("\n");
                //清空输出流的发送区域,将信息发送到网上
                bufferedWriter.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
